<template>
  <div class="app-container">
    <el-row>
      <el-card>
        <el-row class="text-right m-b">
          <el-input v-model="search" placeholder="输入关键字搜索" style="width: 400px;" />
          <el-button icon="el-icon-plus" type="primary" @click="handleAdd()">添加物品</el-button>
          <el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" style="width: 100%" stripe="true" maxheight="100">
            <!-- label是显示的标签，prob是对应data当中的名称，每一个对象当中都应该包含prop -->
            <el-table-column label="序号" align="center" type="index" :index="indexMethod" width="50%" prop="materialsId" />
            <!-- 物品名称 -->
            <el-table-column label="物品名称" prop="materialsName" align="center">
              <template slot-scope="{row}">
                <span>{{ row.materialsName }}</span>
              </template>
            </el-table-column>
            <!-- 物品图片 -->
            <!-- <el-table-column label="物品图片" prop="image" align="center">
              <template slot-scope="{row}">
                <img :src="row.image" style="max-width: 100px; max-height: 100px;">
              </template>
            </el-table-column> -->
            <!-- 地点 -->
            <el-table-column label="地点" prop="materialsPlace" align="center">
              <template slot-scope="{row}">
                <span>{{ row.materialsPlace }}</span>
              </template>
            </el-table-column>
            <!-- 数量 -->
            <el-table-column label="数量" prop="materialsCount" align="center">
              <template slot-scope="{row}">
                <span>{{ row.materialsCount }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-card>
    </el-row>
    <!-- 编辑物品的弹窗显示 -->
    <el-dialog :visible.sync="dialogEditFormVisible" width="30%">
      <el-form ref="tempTableData" :model="tempTableData" :rules="rules" label-position="center" label-width="90px">
        <el-form-item label="物品名称" prop="materialsName">
          <el-input v-model="tempTableData.materialsName" />
        </el-form-item>
        <el-form-item label="地址" prop="materialsPlace">
          <el-cascader
            v-model="tempTableData.materialsPlace"
            :options="options"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择位置"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="数量" prop="materialsCount">
          <el-input-number v-model="tempTableData.materialsCount" :min="1" :max="10000" @change="handleChange" />
        </el-form-item>
        <!-- <el-form-item label="上传图片" prop="image">
          <el-upload
            class="upload-demo"
            action="#"
            :on-preview="handlePicturePreview"
            :on-remove="handlePictureRemove"
            :file-list="tempTableData.image"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="editData()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 新增物品的弹窗显示 -->
    <el-dialog :visible.sync="dialogAddFormVisible" width="30%">
      <el-form ref="tempTableData" :model="tempTableData" :rules="rules" label-position="center" label-width="90px">
        <el-form-item label="物品名称" prop="materialsName" width="100%">
          <el-input v-model="tempTableData.materialsName" />
        </el-form-item>
        <el-form-item label="地址" prop="materialsPlace" width="100%">
          <el-cascader
            v-model="tempTableData.materialsPlace"
            :options="options"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择位置"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="数量" prop="materialsCount" width="100%">
          <el-input-number v-model="tempTableData.materialsCount" :min="1" :max="10000" @change="handleChange" />
        </el-form-item>
        <!-- <el-form-item label="上传图片" prop="image">
          <el-upload
            class="upload-demo"
            action="#"
            :on-preview="handlePicturePreview"
            :on-remove="handlePictureRemove"
            :file-list="tempTableData.image"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="addData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMaterials, refrushMaterials, deleteMaterials, addMaterials } from '@/api/storehouseManage'

export default {
  data() {
    return {
      tableData: [],
      options: [{
        value: '1楼',
        label: '1楼',
        children: [{
          value: '114',
          label: '114'
        }, {
          value: '118',
          label: '118'
        }]
      }, {
        value: '2楼',
        label: '2楼',
        children: [{
          value: '214',
          label: '214'
        }, {
          value: '215',
          label: '215'
        }, {
          value: '216',
          label: '216'
        }, {
          value: '217',
          label: '217'
        }, {
          value: '218',
          label: '218'
        }]
      }, {
        value: '3楼',
        label: '3楼',
        children: [{
          value: '314',
          label: '314'
        }, {
          value: '315',
          label: '315'
        }, {
          value: '316',
          label: '316'
        }, {
          value: '317',
          label: '317'
        }, {
          value: '318',
          label: '318'
        }]
      }, {
        value: '4楼',
        label: '4楼',
        children: [{
          value: '414',
          label: '414'
        }, {
          value: '415',
          label: '415'
        }, {
          value: '416',
          label: '416'
        }, {
          value: '417',
          label: '417'
        }, {
          value: '418',
          label: '418'
        }]
      }],
      tempTableData: [{
        materialsId: '',
        materialsName: '',
        materialsPlace: '',
        materialsCount: '',
        image: ''
      }],
      search: '',
      dialogEditFormVisible: false,
      dialogAddFormVisible: false,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        address: [{ required: true, message: '请选择位置', trigger: 'change' }],
        amount: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchMaterials()
  },
  methods: {
    async fetchMaterials() {
      try {
        const response = await getMaterials()
        console.log(response)
        this.tableData = response.data.materialsList
      } catch (error) {
        console.error('Error fetching materials:', error)
      }
    },
    handleChange(value) {
      console.log(value)
    },
    handleEdit(row) {
      console.log('1')
      this.tempTableData = Object.assign({}, row)
      this.tempTableData.materialsId = row.materialsId
      this.tempTableData.materialsName = row.materialsName

      const addressParts = row.materialsPlace.split('/')
      const building = addressParts[0]
      const room = addressParts[1]
      const buildingOption = this.options.find(option => option.value === building)
      if (buildingOption) {
        this.tempTableData.materialsPlace = [building, room]
      }

      this.tempTableData.materialsCount = row.materialsCount
      // console.log('2')
      this.dialogEditFormVisible = true
    },
    // 现在想要实现的效果是，更新完数据之后，数据要能够直接显示在原表单里。
    editData() {
      this.tempTableData.materialsPlace = this.tempTableData.materialsPlace.join('/')
      this.$refs['tempTableData'].validate((valid) => {
        if (valid) {
          const index = this.tableData.findIndex(item => item.materialsId === this.tempTableData.materialsId)
          console.log(index)
          if (index !== -1) {
            refrushMaterials({
              'materialsId': this.tempTableData.materialsId,
              'materialsName': this.tempTableData.materialsName,
              'materialsPlace': this.tempTableData.materialsPlace,
              'materialsCount': this.tempTableData.materialsCount
            })
              .then(res => {
                console.log(res.data)
                this.fetchMaterials()
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.cancleAction()
              })
              .catch(error => {
                console.error('Error updating materials:', error)
                this.$message({
                  showClose: true,
                  message: '修改失败，请重试！',
                  type: 'error'
                })
              })
          }
        } else {
          this.$message({
            showClose: true,
            message: '请检查信息是否填写完整！',
            type: 'error'
          })
        }
      })
    },
    cancleAction() {
      this.dialogAddFormVisible = false
      this.dialogEditFormVisible = false
      this.tempTableData = [{
        materialsId: '',
        materialsName: '',
        materialsPlace: '',
        materialsCount: ''
      }]
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除此物品，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning' }).then(() => { // 找到要删除的员工在数组中的索引
        const index = this.tableData.indexOf(row) // 从数组中删除员工
        /* 找到员工之后删除员工 */
        console.log(this.tableData[index].materialsId)
        deleteMaterials(this.tableData[index].materialsId)
          .then(res => {
            console.log(res.data)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.fetchMaterials()
          })
          .catch(error => {
            console.error('Error updating materials:', error)
            this.$message({
              showClose: true,
              message: '删除失败，请重试！',
              type: 'error'
            })
          })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      }
      )
      console.log(index, row)
    },
    // 设置ID号
    indexMethod(index) {
      return index + 1
    },
    handleAdd() {
      this.cancleAction()
      this.dialogAddFormVisible = true
    },
    addData() {
      this.tempTableData.materialsPlace = this.tempTableData.materialsPlace.join('/')
      this.$refs['tempTableData'].validate((valid) => {
        if (valid) {
          this.$confirm('确认要添加此物品？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning' }).then(() => {
            addMaterials({
              materialsName: this.tempTableData.materialsName,
              materialsPlace: this.tempTableData.materialsPlace,
              materialsCount: this.tempTableData.materialsCount
            })
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '增加成功!'
                })
                this.cancleAction()
                this.fetchMaterials()
              })
              .catch(error => {
                console.error('Error updating materials:', error)
                this.$message({
                  showClose: true,
                  message: '增加失败，请重试！',
                  type: 'error'
                })
              })
          })
        } else {
          this.$message({
            showClose: true,
            message: '请检查信息是否填写完整！',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
